<template>
  <div class="jdf-editor-container">
    <!-- <div class="editor-toolbar">
      <el-button :icon="Refresh" @click="applyChanges" :disabled="!editorStore.hasLoadedFile">应用到可视化</el-button>
      <el-button :icon="MagicStick" @click="formatCode" :disabled="!editorStore.hasLoadedFile">格式化XML</el-button>
      <el-alert v-if="editorStore.error" type="error" show-icon :closable="false" class="editor-error-alert">
        <template #title>解析/格式化错误</template>
        {{ editorStore.error }}
      </el-alert>
    </div> -->
    <div ref="editorContainer" class="editor-instance"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import * as monaco from 'monaco-editor'
import { useSettingsStore } from '@/stores/settingsStore'
import { useEditorStore } from '@/stores/editorStore.ts'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh, MagicStick } from '@element-plus/icons-vue'

const editorContainer = ref<HTMLElement | null>(null)
let editorInstance: monaco.editor.IStandaloneCodeEditor | null = null
const settingsStore = useSettingsStore()
const editorStore = useEditorStore()

let isSettingContent = false

onMounted(() => {
  if (editorContainer.value) {
    editorInstance = monaco.editor.create(editorContainer.value, {
      value: editorStore.rawContent,
      language: 'xml',
      theme: settingsStore.darkMode ? 'vs-dark' : 'vs',
      readOnly: !editorStore.hasLoadedFile,
      automaticLayout: true,
      minimap: { enabled: true },
      wordWrap: 'on',
      lineNumbers: 'on',
      scrollBeyondLastLine: false,
      folding: true
    })

    editorInstance.onDidChangeModelContent(() => {
      if (editorInstance && !isSettingContent) {
        const currentValue = editorInstance.getValue()
        editorStore.handleEditorChange(currentValue)
      }
    })

    watch(() => editorStore.rawContent, (newContent) => {
      if (editorInstance && editorInstance.getValue() !== newContent) {
        isSettingContent = true
        const editorState = editorInstance.saveViewState()
        editorInstance.setValue(newContent)
        if (editorState) {
          editorInstance.restoreViewState(editorState)
        }
        isSettingContent = false
      }
    })

    watch(() => settingsStore.darkMode, (isDark) => {
      monaco.editor.setTheme(isDark ? 'vs-dark' : 'vs')
    })

    watch(() => editorStore.hasLoadedFile, (hasLoaded) => {
      editorInstance?.updateOptions({ readOnly: !hasLoaded })
    }, { immediate: true })
  }
})

onBeforeUnmount(() => {
  editorInstance?.dispose()
})

const applyChanges = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要将编辑器内容应用到可视化界面吗？',
      '应用更改',
      {
        confirmButtonText: '确定应用',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    await editorStore.applyEditorChangesToVisualizer()
  } catch {
    ElMessage.info('应用操作已取消。')
  }
}

const formatCode = async () => {
  await editorStore.formatXml()
}
</script>

<style scoped>
.jdf-editor-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

.editor-toolbar {
  padding: 5px 10px;
  border-bottom: 1px solid var(--el-border-color);
  flex-shrink: 0;
  display: flex;
  align-items: center;
  gap: 10px;
}

.editor-instance {
  flex-grow: 1;
  overflow: hidden;
}

.editor-error-alert {
  margin-left: auto;
}
</style>